package io.github.loserYa.config;

import io.github.loserYa.enable.EnableRegister;
import io.github.loserYa.mutil.RabbitFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.Environment;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 获取注解上的信息 进行多数据源配置
 *
 * @author loser
 * @date 2024/4/25
 */
public class RabbitRegister {

    private final Set<String> pres = new HashSet<>();

    public RabbitRegister(ConfigurableListableBeanFactory beanFactory, Environment environment) {

        try {
            Map<String, Object> beansWithAnnotation = beanFactory.getBeansWithAnnotation(EnableRegister.class);
            beansWithAnnotation.forEach((key, value) -> {
                EnableRegister proxy;
                try {
                    Class<?> aClass = Class.forName(beanFactory.getBeanDefinition(key).getBeanClassName().split("\\$")[0]);
                    proxy = aClass.getAnnotation(EnableRegister.class);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
                for (String pre : proxy.pre()) {
                    if (Objects.nonNull(pre)) {
                        pres.add(pre);
                    }
                }
            });
        } catch (Exception ignore) {
        }
        for (String pre : pres) {
            beanFactory.registerSingleton(pre + "RabbitFactory", new RabbitFactory(pre, beanFactory, environment));
        }

    }

}
